<script lang="ts" setup>
	import {onLoad} from '@dcloudio/uni-app';
	import {computed, ref} from 'vue';
	import useSparePartTypeListService from './services/useSparePartTypeListService';
	import useSparePartListService from './services/useSparePartListService';
	import useSparePartApplyMaterialSelectedListService from './services/useSparePartApplyMaterialSelectedListService';
	import {SaprePartApplySelectedMaterial, SparePartListItem} from './types';
	import useSparePartBomListService from './services/useSparePartBomListService';

const {bomList, getBomListParam, getBomList} =
		useSparePartBomListService();
	const {
		materialSelectedList,
		materialIsNotBomSelectedSpareIdList,
		materialIsNotBomSelectedSpecIdList,
		addSelectedMaterial,
		removeSelectedMaterial,
	} = useSparePartApplyMaterialSelectedListService();
	const {total, sparePartList, getSparePartListParam, getSparePartList} =
		useSparePartListService();
	const {sparePartTypeList, getSparePartTypeList} =
		useSparePartTypeListService();

	defineOptions({
		name: 'SparePartApplySelectMaterial',
	});

	const pageStyle = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		return {
			height: `${systemInfo.windowHeight - systemInfo.safeAreaInsets.bottom}px`,
			width: `${systemInfo.windowWidth}px`,
		};
	});

	const footerStyle = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		return {
			bottom: `${systemInfo.safeAreaInsets.bottom}px`,
		};
	});

	const typeListStyle = computed(() => {
		if (materialSelectedList.value.length >= 1) {
			return {
				paddingBottom: '128rpx',
			};
		}

		return {
			padding: '0',
		};
	});

	const materialListStyle = computed(() => {
		if (materialSelectedList.value.length >= 1) {
			return {
				padding: '24rpx 24rpx 128rpx 24rpx',
			};
		}

		return {
			padding: '24rpx',
		};
	});

	const currentActiveTypeId = ref('');
	const refreshState = ref(false);
	const detailPopupInstance = ref();
	const detailPopupState = ref(false);

	const handleTypeClick = async (typeId: string) => {
		currentActiveTypeId.value = typeId;
		getSparePartListParam.value.typeId = typeId;
		await getList(false, false);
	};

	const hadnleScrollToLower = async (data) => {
		if (data.detail.direction === 'bottom') {
			const {page, limit} = getSparePartListParam.value;
			if (page * limit < total.value) {
				getSparePartListParam.value.page += 1;
				await getSparePartList();
			}
		}
	};

	const handleReFresherRefresh = async (data) => {
		refreshState.value = true;
		getSparePartListParam.value.page = 1;
		await getSparePartList();
		refreshState.value = false;
	};

	const handleAddClick = (data: SparePartListItem) => {
		data.applyQty = 1;
		addSelectedMaterial({
			id: '',
			spareCode: data.code,
			spareId: data.id,
			spareName: data.name,
			applyQty: 1,
			actualSendQty: 0,
			spareModel: data.model,
			specId: data.specId,
			specName: data.specName,
			type: data.type,
			unit: data.unit,
			price: data.price,
			remark: '',
			urgentLevel: 1,
			stock: data.storeQty - data.freezeQty,
			isBom: 0,
			brand: data.brand
		});
	};

	const handleRemoveClick = (spareId: string, specId: string) => {
		removeSelectedMaterial(spareId, specId);
		if (materialSelectedList.value.length <= 0) {
			onDetailClick();
		}
	};

	const onDetailClick = () => {
		detailPopupState.value = !detailPopupState.value;
		if (detailPopupInstance.value) {
			if (detailPopupState.value) {
				detailPopupInstance.value.open();
			}

			if (!detailPopupState.value) {
				detailPopupInstance.value.close();
			}
		}
	};

	const onConfirmClick = () => {
		uni.redirectTo({
			url: '/pages_network/home/parts/addParts'
		});
	};

	const handleQueryBomClick = async (sparePart: SparePartListItem) => {
		await getBomList(sparePart.id)
		if (bomList.value.length <= 0) {
			uni.showModal({
				title: '提示',
				content: '没有BOM子件信息',
			})
			return
		}
		uni.navigateTo({
			url: `/pages_network/home/parts/selectBoms?id=${sparePart.id}`,
		});
	};

	const getList = async (isGetTypeList = false, isAppend = true) => {
		uni.showLoading({
			mask: true,
			title: '加载中',
		});
		if (isGetTypeList) {
			await getSparePartTypeList();
		}
		await getSparePartList(isAppend);
		uni.hideLoading();
	};

	const init = async () => {
		await getList(true);
	};

	onLoad(() => {
		init();
	});
</script>

<template>
	<view class="spare-part-apply-select-material" :style="pageStyle">
		<view class="search-box">
			<view class="search">
				<uni-icons type="search" size="20" color="#999999"></uni-icons>
				<input
					class="uni-input"
					confirm-type="search"
					placeholder="输入商品名称/型号/编码/规格名称搜索"
					v-model.trim="getSparePartListParam.keyword"
					@confirm="getList(false, false)"
				/>
				<view class="btn" @click="getList(false, false)">搜索</view>
			</view>
		</view>
		<view class="body">
			<view class="type-list" :style="typeListStyle">
				<view
					:class="{'type-item': true, active: currentActiveTypeId === ''}"
					@click="handleTypeClick('')"
				>
					全部分类
				</view>
				<view
					:class="{
						'type-item': true,
						active: currentActiveTypeId === typeOption.id,
					}"
					v-for="(typeOption, typeOptinIndex) in sparePartTypeList"
					:key="typeOptinIndex"
					@click="handleTypeClick(typeOption.id)"
				>
					{{ typeOption.name }}
				</view>
			</view>
			<scroll-view
				class="material-list"
				scroll-y="true"
				:style="materialListStyle"
				@scrolltolower="hadnleScrollToLower"
				:refresher-enabled="true"
				:refresher-triggered="refreshState"
				@refresherrefresh="handleReFresherRefresh"
			>
				<view
					class="material-item"
					v-for="(sparePartOption, sparePartOptionIndex) in sparePartList"
					:key="sparePartOptionIndex"
				>
					<view class="cover-info">
						<view class="cover">
							<uni-icons color="#aac" size="48" type="image"></uni-icons>
						</view>
						<view class="info">
							<!-- <view class="info-item">
								<view class="label">品牌：</view>
								<view class="value">{{ sparePartOption.brand }}</view>
							</view> -->
							<view class="info-item">
								<view class="label">编号：</view>
								<view class="value">{{ sparePartOption.code }}</view>
							</view>
							<view class="info-item">
								<view class="label">名称：</view>
								<view class="value">{{ sparePartOption.name }}</view>
							</view>
							<!-- <view class="info-item">
								<view class="label">图号(同步SAP)：</view>
								<view class="value">{{ sparePartOption.model }}</view>
							</view> -->
							<view class="info-item">
								<view class="label">规格：</view>
								<view class="value">{{ sparePartOption.specName }}</view>
							</view>
							<view class="info-item">
								<view class="label">单价：</view>
								<view class="value">
									￥{{ (sparePartOption.price || 0).toFixed(2) }}
								</view>
							</view>
							<view
								class="info-item"
								@click="handleQueryBomClick(sparePartOption)"
							>
								<view class="label">更多：</view>
								<view class="value" style="color: #007cff">查询BOM</view>
							</view>
						</view>
					</view>
					<view class="btn">
						<uni-icons
							v-if="
								materialIsNotBomSelectedSpareIdList.includes(sparePartOption.id) &&
								materialIsNotBomSelectedSpecIdList.includes(sparePartOption.specId)
							"
							type="minus-filled"
							size="30"
							color="#f56c6c"
							@click="handleRemoveClick(sparePartOption.id, sparePartOption.specId)"
						></uni-icons>
						<uni-icons
							v-else
							type="plus-filled"
							size="30"
							color="#007cff"
							@click="handleAddClick(sparePartOption)"
						></uni-icons>
					</view>
				</view>
			</scroll-view>
		</view>
		<view
			class="footer"
			v-if="materialSelectedList.length > 0"
			:style="footerStyle"
		>
			<view class="content">
				<view class="info">
					<text>已选择</text>
					<text class="num">{{ materialSelectedList.length }}</text>
					<text>个配件</text>
					<view class="detail" @click="onDetailClick">
						明细
						<uni-icons
							type="down"
							size="14"
							color="#007cff"
							v-if="detailPopupState"
						></uni-icons>
						<uni-icons type="up" size="14" color="#007cff" v-else></uni-icons>
					</view>
				</view>

				<view class="confirm-btn" @click="onConfirmClick">确认提交</view>
			</view>
		</view>

		<uni-popup ref="detailPopupInstance" type="bottom" background-color="#fff">
			<view class="detail-popup-content">
				<view class="header">
					<view class="placeholder-icon"></view>
					<view class="title">已选择配件</view>
					<view class="close-btn" @click="onDetailClick">
						<uni-icons type="closeempty" size="18" color="#000"></uni-icons>
					</view>
				</view>
				<view class="material-selected-list">
					<view
						class="material-selected-item"
						:key="materialSelectedOptionIndex"
						v-for="(
							materialSelectedOption, materialSelectedOptionIndex
						) in materialSelectedList"
					>
						<view class="cover-info">
							<view class="cover">
								<uni-icons color="#aac" size="48" type="image"></uni-icons>
							</view>
							<view class="info">
								<!-- <view class="info-item">
									<view class="info-label">品牌:</view>
									<view class="info-value">
										{{ materialSelectedOption.brand }}
									</view>
								</view> -->
								<view class="info-item">
									<view class="info-label">编号:</view>
									<view class="info-value">
										{{ materialSelectedOption.spareCode }}
									</view>
								</view>
								<view class="info-item">
									<view class="info-label">名称:</view>
									<view class="info-value">
										{{ materialSelectedOption.spareName }}
									</view>
								</view>
								<view class="info-item">
									<view class="info-label">图号(同步SAP):</view>
									<view class="info-value">
										{{ materialSelectedOption.spareModel }}
									</view>
								</view>
								<view class="info-item">
									<view class="info-label">规格:</view>
									<view class="info-value">
										{{ materialSelectedOption.specName }}
									</view>
								</view>
								<view class="info-item">
									<view class="info-label">单价:</view>
									<view class="info-value">
										￥{{ (materialSelectedOption.price || 0).toFixed(2) }}
									</view>
								</view>
							</view>
						</view>
						<view class="btn">
							<uni-icons
								type="minus-filled"
								size="30"
								color="#f56c6c"
								@click="handleRemoveClick(materialSelectedOption.spareId, materialSelectedOption.specId)"
							></uni-icons>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<style scoped lang="scss">
	.spare-part-apply-select-material {
		display: flex;
		flex-direction: column;
		background-color: #fff;

		.search-box {
			box-sizing: border-box;
			padding: 24rpx;
			width: 100%;

			.search {
				display: flex;
				height: 64rpx;
				font-size: 24rpx;
				background-color: #fff;
				box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
				border-radius: 64rpx;
				align-items: center;
				justify-content: space-between;
				padding: 0 24rpx 0 16rpx;
				column-gap: 12rpx;

				.uni-input {
					flex: 1;
					width: 0;
					font-size: 24rpx;
				}

				.btn {
					color: #007cff;
					font-weight: bold;
					line-height: 28rpx;
				}
			}
		}

		.body {
			flex: 1;
			height: 0;
			width: 100%;
			display: flex;

			.type-list {
				width: 200rpx;
				background-color: #f5f5f5;
				box-sizing: border-box;

				.type-item {
					font-size: 24rpx;
					height: 64rpx;
					display: flex;
					align-items: center;
					box-sizing: border-box;
					padding-left: 32rpx;
					font-weight: bold;
					white-space: nowrap;
				}

				.active {
					color: #007cff;
					background-color: #fff;
				}
			}

			.material-list {
				height: 100%;
				flex: 1;
				width: 0;
				display: flex;
				flex-direction: column;
				box-sizing: border-box;

				.material-item {
					display: flex;
					border: 2rpx solid #eee;
					box-sizing: border-box;
					padding: 12rpx;
					column-gap: 12rpx;
					margin-bottom: 24rpx;
					justify-content: space-between;

					.cover-info {
						display: flex;
						column-gap: 12rpx;

						.cover {
							min-width: 124rpx;
							min-height: 124rpx;
							max-width: 124rpx;
							max-height: 124rpx;
							border: 2rpx solid #eee;
						}

						.info {
							display: flex;
							flex-direction: column;
							font-size: 24rpx;

							.info-item {
								display: flex;

								.label {
									white-space: nowrap;
									color: #606266;
								}
							}
						}
					}
				}
			}
		}

		.footer {
			padding: 24rpx;
			box-sizing: border-box;
			position: fixed;
			left: 0;
			right: 0;
			z-index: 999;
			background-color: #fff;

			.content {
				width: 100%;
				height: 72rpx;
				background-color: #f5f7fa;
				border-radius: 72rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.info {
					display: flex;
					align-items: center;
					padding-left: 32rpx;
					font-size: 24rpx;
					font-weight: bold;

					.num {
						color: #007cff;
					}

					.detail {
						color: #007cff;
						margin-left: 8rpx;
					}
				}

				.confirm-btn {
					width: 148rpx;
					height: 100%;
					background-color: #007cff;
					color: #fff;
					font-size: 28rpx;
					font-weight: bold;
					display: flex;
					justify-content: center;
					align-items: center;
					border-top-right-radius: 72rpx;
					border-bottom-right-radius: 72rpx;
				}
			}
		}
	}

	.detail-popup-content {
		height: 70vh;
		width: 100%;
		background-color: #fff;
		padding: 0 0 128rpx 0;
		overflow: auto;
		display: flex;
		flex-direction: column;

		.header {
			display: flex;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 16rpx;

			.title {
				color: #000;
				font-weight: bold;
			}
		}

		.material-selected-list {
			background-color: #f5f5f5;
			flex: 1;
			height: 0;
			display: flex;
			flex-direction: column;
			row-gap: 24rpx;
			box-sizing: border-box;
			padding: 24rpx;
			overflow: auto;

			.material-selected-item {
				display: flex;
				column-gap: 12rpx;
				justify-content: space-between;
				background-color: #fff;
				box-sizing: border-box;
				padding: 24rpx;

				.cover-info {
					display: flex;
					column-gap: 12rpx;

					.cover {
						min-width: 124rpx;
						min-height: 124rpx;
						max-width: 124rpx;
						max-height: 124rpx;
						border: 2rpx solid #eee;
					}

					.info {
						display: flex;
						flex-direction: column;

						.info-item {
							font-size: 24rpx;
							display: flex;
							column-gap: 8rpx;

							.info-label {
								color: #606266;
								white-space: nowrap;
							}
						}
					}
				}
			}
		}
	}
</style>
